/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AsignacionDeFunciones.java
 *
 * Created on 21-jul-2011, 22:56:29
 */
package ventanas;

import conexiones.AdministradorDeConexiones;
import dao.FuncionesDao;
import dao.PerfilesDao;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.DefaultListModel;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import modelo.Funcion;
import modelo.Perfil;

/**
 *
 * @author M.G
 */
public class AsignacionDeFunciones extends javax.swing.JDialog {
    private DefaultListModel funcionPerfil ;
    private DefaultListModel funcionDisponible;
    private Connection conn = null;
    private ArrayList<Funcion> listaAuxiliar;
    private Perfil perfil = null;
    
       /**
     * @return the usuarioLogueado
     */
    public Perfil getPerfil() {
        return perfil;
    }

    /**
     * @param usuarioLogueado the usuarioLogueado to set
     */
    public void setPerfil(Perfil perfil) {
        this.perfil = perfil;
    }
    
     /** Creates new form AsignacionDeFunciones */
    public AsignacionDeFunciones(JDialog parent, boolean modal) {
        super(parent, modal);
        initComponents();
        funcionPerfil = (DefaultListModel) listFuncionPerfil.getModel();
        funcionDisponible = (DefaultListModel) listFuncionDisponible.getModel();
        this.pack();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listFuncionPerfil = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        listFuncionDisponible = new javax.swing.JList();
        jPanel3 = new javax.swing.JPanel();
        btnAceptar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        btnIzquierda = new javax.swing.JButton();
        btnDerecha = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Asignación de funciones al perfil: ");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jPanel1.setPreferredSize(new java.awt.Dimension(268, 363));

        listFuncionPerfil.setModel(new javax.swing.DefaultListModel());
        listFuncionPerfil.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listFuncionPerfilMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(listFuncionPerfil);

        jLabel1.setText("Funciones del Perfil:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 317, Short.MAX_VALUE)
                    .addComponent(jLabel1))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 457, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jPanel2.setPreferredSize(new java.awt.Dimension(264, 363));

        jLabel2.setText("Funciones Disponibles:");

        listFuncionDisponible.setModel(new javax.swing.DefaultListModel());
        listFuncionDisponible.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listFuncionDisponibleMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(listFuncionDisponible);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)
                    .addComponent(jLabel2))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 457, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        btnAceptar.setText("Aceptar");
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(255, 255, 255)
                .addComponent(btnAceptar)
                .addGap(98, 98, 98)
                .addComponent(btnCancelar)
                .addContainerGap(249, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAceptar)
                    .addComponent(btnCancelar))
                .addContainerGap())
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        btnIzquierda.setText("<-");
        btnIzquierda.setMinimumSize(new java.awt.Dimension(105, 23));
        btnIzquierda.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnIzquierdaActionPerformed(evt);
            }
        });

        btnDerecha.setText("->");
        btnDerecha.setMinimumSize(new java.awt.Dimension(105, 23));
        btnDerecha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDerechaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnIzquierda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnDerecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(209, 209, 209)
                .addComponent(btnIzquierda, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnDerecha, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(215, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 341, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 332, Short.MAX_VALUE))
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 503, Short.MAX_VALUE)
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 503, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-768)/2, (screenSize.height-596)/2, 768, 596);
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        // Cuando presiona la tecla SI el valor de confirmacionDeCierre() = 0 y se cierra la ventana
            if(confirmacionDeCierre() == 0 ){
                this.dispose();
            }
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
         // Cuando presiona la tecla SI el valor de confirmacionDeCierre() = 0 y se cierra la ventana
            if(confirmacionDeCierre() == 0 ){
                this.dispose();
            }
    }//GEN-LAST:event_formWindowClosing

    private void btnIzquierdaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIzquierdaActionPerformed
        int largo = listFuncionDisponible.getSelectedValues().length -1;
               
        for(int i=0;i <= largo;i++){
            funcionPerfil.addElement(listFuncionDisponible.getSelectedValues()[0]);
            funcionDisponible.removeElement(listFuncionDisponible.getSelectedValues()[0]);
       }        
    }//GEN-LAST:event_btnIzquierdaActionPerformed

    private void btnDerechaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDerechaActionPerformed
        int largo = listFuncionPerfil.getSelectedValues().length -1;
               
        for(int i=0;i <= largo;i++){
            funcionDisponible.addElement(listFuncionPerfil.getSelectedValues()[0]);
            funcionPerfil.removeElement(listFuncionPerfil.getSelectedValues()[0]);
        }
    }//GEN-LAST:event_btnDerechaActionPerformed

    private void listFuncionPerfilMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listFuncionPerfilMouseClicked
        listFuncionDisponible.clearSelection();
    }//GEN-LAST:event_listFuncionPerfilMouseClicked

    private void listFuncionDisponibleMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listFuncionDisponibleMouseClicked
        listFuncionPerfil.clearSelection();
    }//GEN-LAST:event_listFuncionDisponibleMouseClicked

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        cargarListas(perfil.getCod());
        this.setTitle(getTitle() + " " + perfil.getNombre());
    }//GEN-LAST:event_formWindowOpened

    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
       int resultado;
       resultado = JOptionPane.showConfirmDialog(this, "Los cambios realizados serán aplicados al perfil ¿Desea continuar?", "Advertencia", JOptionPane.YES_NO_OPTION);
       if(resultado == 0){
        int largo = funcionPerfil.size() - 1;                
       try {
            conn = AdministradorDeConexiones.obtenerConexion();
            PerfilesDao.getInstance().LimpiarFuncionesAsignadas(conn,perfil.getCod());
            for(int i=0;i <= largo;i++){
                PerfilesDao.getInstance().AsignarFuncionAPerfil(conn, perfil.getCod(),(Funcion)funcionPerfil.get(i));
            }
            this.dispose();
        }catch(Exception e) {e.printStackTrace();}
    }//GEN-LAST:event_btnAceptarActionPerformed
    }
    /**
     * @param args the command line arguments
     */
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnDerecha;
    private javax.swing.JButton btnIzquierda;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JList listFuncionDisponible;
    private javax.swing.JList listFuncionPerfil;
    // End of variables declaration//GEN-END:variables

    public int confirmacionDeCierre(){
        return(JOptionPane.showConfirmDialog(this, "Los cambios realizados se perderán ¿Desea salir?", "Advertencia", JOptionPane.YES_NO_OPTION));
    }

    private void cargarListas(int idPerfil){        
        
        try {
            conn = AdministradorDeConexiones.obtenerConexion();
            listaAuxiliar = FuncionesDao.getInstance().getFuncionesDePerfil(conn, idPerfil);
            cargarFuncionesDePerfil();
            listaAuxiliar = FuncionesDao.getInstance().getFuncionesDisponibles(conn, idPerfil);
            cargarFuncionesDisponibles();
        }catch(Exception e) {e.printStackTrace();}
    }
    
    private void cargarFuncionesDePerfil(){
        Iterator iteraFuncion = listaAuxiliar.iterator();
            while (iteraFuncion.hasNext()) {
                Funcion funcion = (Funcion) iteraFuncion.next();
                funcionPerfil.addElement(funcion);
            }
    }
    
    private void cargarFuncionesDisponibles(){
        Iterator iteraFuncion = listaAuxiliar.iterator();
            while (iteraFuncion.hasNext()) {
                Funcion funcion = (Funcion) iteraFuncion.next();
                funcionDisponible.addElement(funcion);
            }
    }
    
    
}
